package com.hue;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

import javax.servlet.http.*;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author hue
 */

@SuppressWarnings("serial")
public class DantriWebServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html; charset=utf-8");

        if("true".equals(req.getParameter("forward"))) {
        	ArrayList links = (ArrayList) getServletContext().getAttribute(SaveLinks.SAVE_LINKS);
        	if(links != null && !links.isEmpty()) {
        		final int iIndex = new Random().nextInt(links.size());
        		String s = (String) links.get(iIndex);
        		String script = "<script>window.location=\"" + s + "\";</script>";
        		resp.getOutputStream().println(script);
        	}
        	return;
        }
        
        String q = req.getParameter("qx");
        if(q == null || q.isEmpty()) {
        	q = "http://tuoitre.vn";
        }
        byte[] query = Base64.decodeBase64(q.getBytes());

        final URL url = new URL(new String(query));

        final InputStream in = url.openStream();
        byte[] buff = new byte[10240];
        int nByte;
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        while((nByte = in.read(buff)) > 0) {
            out.write(buff, 0, nByte);
        }
        in.close();
        String html = out.toString("utf-8");
        out.close();
        html = setBaseUrl(req, html, url.toString());
        resp.getWriter().print(html);
        resp.getWriter().flush();
    }
    
    private String setBaseUrl(final HttpServletRequest req, final String html, final String url) {
        int iIndex = url.indexOf("://");
        if(iIndex == -1) {
            iIndex = 0;
        }
        else {
            iIndex += 3;
        }
        iIndex = url.indexOf('/', iIndex);
        if(iIndex != -1) {
            final String baseUrl = url.substring(0, iIndex);
            iIndex = html.indexOf("<head");
            iIndex = html.indexOf('>', iIndex);
            if(iIndex != -1) {
                final StringBuilder sb = new StringBuilder();
                sb.append(html.substring(0, iIndex + 1));
                sb.append("\r\n<base href=\"").append(baseUrl).append("\">\r\n");
                final String svUrl = serverURL(req) + req.getContextPath();
                sb.append("<script language=\"javascript\" type=\"text/javascript\">\r\n");
                sb.append("    var adfly_id = 3494584;\r\n");
                sb.append("    var adfly_advert = 'int';\r\n");
                sb.append("    var exclude_domains = [];\r\n");
                sb.append("    var my_server_url = \"" + svUrl + "\";\r\n");
                sb.append("</script>\r\n");

                sb.append("<script src=\"http://cdn.adf.ly/js/link-converter.js\"></script>\r\n");
                sb.append("<script type=\"text/javascript\" src=\"").append(svUrl).append("/scripts/json.js\"></script>\r\n");
                sb.append("<script type=\"text/javascript\" src=\"").append(svUrl).append("/scripts/myAdf.js\"></script>\r\n");
                sb.append(html.substring(iIndex + 1));
                iIndex = sb.indexOf("</body>");
                if(iIndex != -1) {
                    sb.insert(iIndex, "<div id=\"my_adf_bottom_div\" style=\"position:fixed;left:0px; bottom:0px;height:150px;width:150px;background-colorx:red\"></div>\r\n<script language=\"javascript\" type=\"text/javascript\">\r\n    DOMAssistant.DOMReady(initMyAdf);\r\n </script>\r\n");
                }

                return sb.toString();
            }
        }
        return html;
    }
    
    protected String serverURL(final HttpServletRequest request) {
        final StringBuffer url = new StringBuffer();
        final String scheme = request.getScheme();
        int port = request.getServerPort();
        if (port < 0) {
            port = 80;
        } // Work around java.net.URL bug
        url.append(scheme);
        url.append("://");
        url.append(request.getServerName());
        if ((scheme.equals("http") && (port != 80)) ||
            (scheme.equals("https") && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        return url.toString();
    }
}
